package user

import (
	"context"
	"fmt"
	partner "gitee.com/binny_w/gin-partner"
	"gitee.com/binny_w/gin_starter/core"
	roleMdl "gitee.com/binny_w/gin_starter/model/role"
	util2 "gitee.com/binny_w/go-util/v2"
	"github.com/gin-gonic/gin"
	"net/http"
)

func infoFromCtxNoFixer(c *gin.Context) *util2.MysqlRow {
	row, ok := c.Get("user")
	if !ok {
		partner.WriteJsonError(c, http.StatusUnauthorized, "请登录#5")
		return nil
	}
	var uRow *util2.MysqlRow
	if uRow, ok = row.(*util2.MysqlRow); !ok || uRow == nil {
		partner.WriteJsonError(c, http.StatusUnauthorized, "请登录#6")
		return nil
	}
	return uRow
}

func infoFromCtx(c *gin.Context) *util2.MysqlRow {
	uRow := infoFromCtxNoFixer(c)
	if uRow == nil {
		return nil
	}
	if err := infoFixer(c, uRow); err != nil {
		return nil
	}
	return uRow
}

func myInfo(c *gin.Context) {
	uRow := infoFromCtx(c)
	if uRow == nil {
		return
	}
	uRow.Drop("pasd")
	partner.WriteJsonSuccess(c, uRow)
}

func updateMyInfo(c *gin.Context) {
	row := infoFromCtx(c)
	if row == nil {
		return
	}
	newRow := util2.NewMysqlRow()
	sexes := []string{"0", "1", "2"}
	if sex, ok := c.GetPostForm("sex"); ok && util2.InArray(sex, sexes) {
		newRow.Set("sex", sex)
	}
	if avatar, ok := c.GetPostForm("avatar"); ok && avatar != "" {
		newRow.Set("avatar", avatar)
	}
	if sig, ok := c.GetPostForm("signature"); ok && sig != "" {
		newRow.Set("signature", sig)
	}
	if !newRow.IsEmpty() {
		if _, err := core.UserTable.UpdateById(c, newRow, row.ToInt64("id")); err != nil {
			partner.WriteJsonError(c, 700, err.Error())
			return
		}
	}
	defer func() {
		bucket := row.ToStr("avatar_bucket")
		key := row.ToStr("avatar_key")
		if bucket != "" && key != "" && newRow.Has("avatar") {
			_ = core.Storage.DeleteObjects(c, bucket, key)
			return
		}
		bucket = row.ToStr("signature_bucket")
		key = row.ToStr("signature_key")
		if bucket != "" && key != "" && newRow.Has("signature") {
			_ = core.Storage.DeleteObjects(c, bucket, key)
		}
	}()
	partner.WriteJsonSuccess(c, nil)
}

func correctRole(id uint64, role string, update bool) (ret string) {
	if id == 0 {
		return
	}
	role1 := ""
	userId := fmt.Sprintf("user:%d", id)
	if rs, _ := core.Rbac.GetRolesForUser(userId); len(rs) > 0 {
		role1 = rs[0]
	}
	allRoles, _ := roleMdl.All()
	if role != "" && util2.InArray(role, allRoles) && role1 == "" {
		ret = role
		if update {
			go func() {
				_, _ = core.Rbac.AddRolesForUser(userId, role)
			}()
		}
	} else {
		ret = role1
		if role != role1 && update {
			go func() {
				_, _ = MdlUser.Table.UpdateById(context.Background(), &util2.MysqlRow{"role": role1}, id)
			}()
		}
	}
	return
}
